package com.bjsxt;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
/**客户端*/
/*存在缺陷，只有在客户端先发送信息才可以接收服务端发来的信息*/
public class TwoWaySocketClient {
    public static void main(String[] args) {
        Socket socket = null;
        Scanner scanner = null;
        PrintWriter pw = null;
        BufferedReader br = null;
        try{
            /*创建各种对象*/
            //创建Socket 对象
            socket = new Socket("127.0.0.1",8888);
            //创建键输入对象
            scanner = new Scanner(System.in);
            //创建向服务发送的流对象
            pw = new PrintWriter(socket.getOutputStream());
            //创建读取服务发送消息的流的对象
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            while (true){
                //向服务端发送信息
                String str = scanner.nextLine();
                pw.println(str);
                pw.flush();
                //接收信息
                String socketInput = br.readLine();
                System.out.println("服务端说："+socketInput);
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(pw != null){
                pw.close();
            }
            if(br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(scanner != null){
                scanner.close();
            }
        }
    }
}
